//
//  MineViewController.m
//  liangyi
//
//  Created by 张水 on 16/12/15.
//  Copyright © 2016年 yswh. All rights reserved.
//

#import "MineViewController.h"
#import "MineUserInfoView.h"
#import "MineCellModel.h"
#import "MineCell.h"
#import "SettingViewController.h"
//#import "UIViewController+ZYSliderViewController.h"
#import "MainViewController.h"
#import "RegisteredViewController.h"
#import "PersonViewController.h"
#import "LoginViewController.h"
#import "MyschemeViewController.h"
#import "RemindViewController.h"
//#import "MMDrawerController.h"
//#import "UIViewController+MMDrawerController.h"
@interface MineViewController ()<UITableViewDelegate,UITableViewDataSource,UIAlertViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIActionSheetDelegate>{
    UIAlertView *alertView;
}

@property(nonatomic,strong) NSArray *arrData;

@property(nonatomic,strong) UITableView *tableView;

@property(nonatomic,strong) UIImagePickerController *imagePickerController;

@property(nonatomic,strong) MineUserInfoView *headerView;

@property(nonatomic,strong) UserModel *model;

@property(nonatomic,strong) UINavigationController *nav;

@end

@implementation MineViewController

static NSString *Minecell = @"Minecell";

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initUI];
    [[NSNotificationCenter  defaultCenter]addObserver:self selector:@selector(JPushJumpToMySchemeVC) name:@"JPushJumpToMySchemeVC" object:nil];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self updateNewData];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
     [self.navigationController setNavigationBarHidden:NO animated:YES];
}

-(NSArray *)arrData {
    
    if (!_arrData){
        NSString *path = [[NSBundle mainBundle]pathForResource:@"MineInfo.plist" ofType:nil];
        NSArray *tempArr = [NSArray arrayWithContentsOfFile:path];
        NSMutableArray *mutable = [NSMutableArray array];
        for (NSDictionary *dict in tempArr) {
            MineCellModel *cellModel = [MineCellModel cellWithDict:dict];
            [mutable addObject:cellModel];
        }
        _arrData = mutable;
    }
    return  _arrData;
    
}

- (void)updateNewData{
    
    NSString *userLogin = [CommonMethod fuckNULL:[UserDefaultsUtlis getValueForKey:@"userid"]];
    if (userLogin.length > 0) {
        [self loadUserInfo];
        self.headerView.loginBtn.hidden = YES;
        self.headerView.registBtn.hidden = YES;
        self.headerView.userName.hidden = NO;
        self.headerView.changInfoBtn.hidden = NO;
    }else{
        self.headerView.loginBtn.hidden = NO;
        self.headerView.registBtn.hidden = NO;
        self.headerView.userName.hidden = YES;
        self.headerView.changInfoBtn.hidden = YES;
        self.headerView.userIcon.image = [UIImage imageNamed:@"user"];
    }

}

-(void)initUI{
    
    self.headerView = [[MineUserInfoView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 150)];
    [self.headerView.userIcon sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/%@",BaseIamgeUrl,self.model.userHead]] placeholderImage:[UIImage imageNamed:@"user"]];
    UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(changUserIcon)];
    [self.headerView.userIcon addGestureRecognizer:gesture];
    [self.headerView.changInfoBtn addTarget:self action:@selector(jumpToPersonVC) forControlEvents:UIControlEventTouchUpInside];
    [self.headerView.loginBtn addTarget:self action:@selector(loginBtnDidClick) forControlEvents:UIControlEventTouchUpInside];
    [self.headerView.registBtn addTarget:self action:@selector(registBtnDidClick) forControlEvents:UIControlEventTouchUpInside];
    
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 30, kScreenWidth - 50, kScreenHeight) style:UITableViewStylePlain];
    self.tableView.backgroundColor = [UIColor ColorWithHex:@"#333942"];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.scrollEnabled = NO;
    self.tableView.tableHeaderView = self.headerView;
    [self.view addSubview:self.tableView];
    [self.tableView registerClass:[MineCell class] forCellReuseIdentifier:Minecell];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.arrData.count;;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    MineCell *mineCell = [tableView dequeueReusableCellWithIdentifier:Minecell];
    mineCell.selectionStyle = UITableViewCellSeparatorStyleNone;
    if (!mineCell) {
        mineCell = [mineCell initWithStyle:UITableViewCellStyleDefault reuseIdentifier:Minecell];
    }
    mineCell.CellModel = self.arrData[indexPath.row];
    
    return mineCell;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
  
    return  70;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    AppDelegate *tempAppDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    if (indexPath.row == 0){
        NSString *userLogin = [CommonMethod fuckNULL:[UserDefaultsUtlis getValueForKey:@"userid"]];
        if (userLogin.length == 0) {
            [CustomProgressHUD showSuccessWithStatus:@"请先登录"];
            return;
        }
        MyschemeViewController *vc = [[MyschemeViewController alloc] init];
        [tempAppDelegate.LeftSlideVC closeLeftView];//关闭左侧抽屉
        [tempAppDelegate.mainNavigationController pushViewController:vc animated:NO];
    }
    
    if (indexPath.row == 1){
        RemindViewController  *vc = [[RemindViewController  alloc] init];
        [tempAppDelegate.LeftSlideVC closeLeftView];//关闭左侧抽屉
        [tempAppDelegate.mainNavigationController pushViewController:vc animated:NO];
    }
    
    if (indexPath.row == 2){
        SettingViewController  *vc = [[SettingViewController  alloc] init];
        [tempAppDelegate.LeftSlideVC closeLeftView];//关闭左侧抽屉
        [tempAppDelegate.mainNavigationController pushViewController:vc animated:NO];
        
    }
    
}

-(void)JPushJumpToMySchemeVC{
    NSString *userLogin = [CommonMethod fuckNULL:[UserDefaultsUtlis getValueForKey:@"userid"]];
    if (userLogin.length == 0) {
        [CustomProgressHUD showSuccessWithStatus:@"请先登录"];
        return;
    }
   AppDelegate *tempAppDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    MyschemeViewController *vc = [[MyschemeViewController alloc] init];
    [tempAppDelegate.LeftSlideVC closeLeftView];//关闭左侧抽屉
    [tempAppDelegate.mainNavigationController pushViewController:vc animated:NO];

}

-(void)loadUserInfo{
    
    NSString *url = [BASEURL stringByAppendingString:kURL_GetUserInfo];
    NSDictionary *dict = @{@"login":[NSString  AES128Encrypt:[NSString stringWithFormat:@"%@@@%@",[[NSUserDefaults standardUserDefaults]objectForKey:@"userid"],ApplicationDelegate.deviceID]]};
    NSLog(@"%@",dict);
    [AppNetwork requestWithPath:url parameters:dict success:^(id responseObject) {
        NSLog(@"%@",responseObject);
        NetworkModel *network = [NetworkModel mj_objectWithKeyValues:responseObject];
        NSInteger code = network.code.integerValue;
        if (code == 0){
            UserModel *model = [UserModel mj_objectWithKeyValues:network.dataObject];
            self.model = model;
            NSLog(@"%@",model.id);
            [UserDefaultsUtlis saveValue:model.id forKey:@"userid"];
            [UserDefaultsUtlis saveValue:model.userPhone forKey:@"userPhone"];
            [Sp_MemberStorage updateMemberWithUserModel:model];
            [self.headerView loadUserData:model];
        }else{
            [Sp_MemberStorage deleteAllMembers];
            [UserDefaultsUtlis removeObjectForKey:@"userid"];
            LoginViewController *vc = [[LoginViewController alloc] init];
            AppDelegate *tempAppDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
            [tempAppDelegate.LeftSlideVC closeLeftView];//关闭左侧抽屉
            UINavigationController *nacvc = [[UINavigationController alloc]initWithRootViewController:vc];
            [tempAppDelegate.mainNavigationController presentViewController:nacvc animated:YES completion:nil];
        }
    } failure:^(id error) {
        [CustomProgressHUD showErrorWithStatus:k_NetWorkStatus_Error];
    }];
    

    
}

-(void)changUserIcon{
    UIActionSheet *sheet = [[UIActionSheet alloc]initWithTitle:@"修改头像" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"从相册选取",@"相机", nil];
    [sheet showInView:self.view];
    
}

#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    if (buttonIndex == 0) {
        self.imagePickerController = [[UIImagePickerController alloc]init];
        self.imagePickerController.delegate = self;
        self.imagePickerController.allowsEditing = YES;
        self.imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentViewController:self.imagePickerController animated:YES completion:nil];
        
    }
    
    if (buttonIndex == 1) {
        self.imagePickerController = [[UIImagePickerController alloc]init];
        self.imagePickerController.delegate = self;
        self.imagePickerController.allowsEditing = YES;
        UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
        if (![UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
            sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        }
        self.imagePickerController.sourceType = sourceType;
        [self presentViewController:self.imagePickerController animated:YES completion:nil];
    }
    
}

#pragma mark - image picker control delegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    
    [self dismissViewControllerAnimated:YES completion:^{
        
        self.headerView.userIcon.image =[info objectForKey:UIImagePickerControllerEditedImage];
        [self submitIconNetwork];
    }];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [self dismissViewControllerAnimated:YES completion:nil];
}


-(void)submitIconNetwork{
    
    CGSize size = CGSizeMake(self.headerView.userIcon.image.size.width * 0.2, self.headerView.userIcon.image.size.height *0.2);
    UIImage *image = [CommonMethod imageWithImage:self.headerView.userIcon.image scaledToSize:size];
    NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
    NSString *imgData = [NSData encodeBase64Data:imageData];
    NSString *url = [BASEURL stringByAppendingString:kURl_ChangHead];
    NSDictionary *dict = @{@"photo":imgData};
    NSString *jsonString = [NSString dictionaryToJson:dict];
    NSString *AESString = [NSString AES128Encrypt:jsonString];
    NSDictionary *parameters = @{@"parameters":AESString,
                                 @"login":[NSString  AES128Encrypt:[NSString stringWithFormat:@"%@@@%@",[[NSUserDefaults standardUserDefaults]objectForKey:@"userid"],ApplicationDelegate.deviceID]]};
    [AppNetwork requestWithPath:url parameters:parameters success:^(id responseObject) {
        NetworkModel *network = [NetworkModel mj_objectWithKeyValues:responseObject];
        NSInteger code = network.code.integerValue;
        if (code == 0){
            [CustomProgressHUD showSuccessWithStatus:@"修改头像成功!!!"];
        }
    } failure:^(id error) {
        [CustomProgressHUD showErrorWithStatus:k_NetWorkStatus_Error];
    }];

}



-(void)jumpToPersonVC{
    PersonViewController *vc = [[PersonViewController alloc] init];
     AppDelegate *tempAppDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [tempAppDelegate.LeftSlideVC closeLeftView];//关闭左侧抽屉
    [tempAppDelegate.mainNavigationController pushViewController:vc animated:NO];
}

-(void)loginBtnDidClick{
    LoginViewController *vc = [[LoginViewController alloc] init];
     AppDelegate *tempAppDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [tempAppDelegate.LeftSlideVC closeLeftView];//关闭左侧抽屉
    UINavigationController *nacvc = [[UINavigationController alloc]initWithRootViewController:vc];
    [tempAppDelegate.mainNavigationController presentViewController:nacvc animated:YES completion:nil];
}
-(void)registBtnDidClick{
    RegisteredViewController *vc = [[RegisteredViewController alloc] init];
     AppDelegate *tempAppDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [tempAppDelegate.LeftSlideVC closeLeftView];//关闭左侧抽屉
     UINavigationController *nacvc = [[UINavigationController alloc]initWithRootViewController:vc];
    [tempAppDelegate.mainNavigationController presentViewController:nacvc animated:YES completion:nil];
}

- (void)dealloc{
    NSLog(@"我的控制器");
}

- (NSString*)dictionaryToJson:(NSData *)data{
    NSError *parseError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:data options:NSJSONWritingPrettyPrinted error:&parseError];
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
}


@end
